<?php
/*
 * @Description    : 短信发送
 * @Author         : QianLong
 * @Date           : 2023-01-11 12:13:55
 * @LastEditors    : QianLong
 * @Site           : http://21ds.cn
 * @LastEditTime   : 2024-04-20 10:54:47
 */

declare(strict_types=1);

namespace App\Controller;

use App\Constants\Status;
use App\Exception\ApiException;
use App\Service\Common;
use App\Service\Schedule;
use Hyperf\Di\Annotation\Inject;
use Qianlong\Validate\Validate;

class ScheduleController extends AbstractController
{
  #[Inject()]
  protected Schedule $schedule;

  public function save()
  {
    $valitor = new Validate();
    $valitor->addColumn('content')->required();
    $valitor->addColumn('start_date')->required();
    $valitor->addColumn('cate')->required();
    $valitor->addColumn('is_loop')->required();
    $valitor->addColumn('notice_open')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $param['is_force'] = ($param['is_force'] == 1 || $param['is_force'] == '1') ? true : false;
    $saveData['content'] = $param['content'];
    $saveData['start_date'] = $param['start_date'];
    $saveData['end_date'] = (isset($param['end_date']) && !empty($param['end_date'])) ? $param['end_date'] : $param['start_date'];
    $saveData['cate'] = $param['cate'];
    $saveData['color'] = $param['color'];
    $saveData['ps_id'] = $param['ps_id'];
    $saveData['desc'] = $param['desc'];
    $saveData['start_time'] = isset($param['start_time']) ? $param['start_time'] : '';
    $saveData['end_time'] = isset($param['end_time']) ? $param['end_time'] : '';
    $saveData['loop_type'] = $param['loop_type'];
    $saveData['date_type'] = $param['date_type'];
    $saveData['importance'] = $param['importance'];
    $saveData['loop_num'] = intval($param['loop_num']);
    $saveData['is_loop'] = intval($param['is_loop']);
    $saveData['before_num'] = isset($param['before_num']) ? intval($param['before_num']) : 0;
    $saveData['notice_open'] = intval($param['notice_open']);
    $userInfo = $this->dataResource->getUserInfo();
    $remoteIp = $this->dataResource->getClientIp($this->request);
    $saveData['client_ip'] = $remoteIp;
    $saveData['step'] = 'step1,'. $param['is_force'];
    $start_event_date_str = !empty($saveData['start_time']) ? $saveData['start_date'] . ' ' . $saveData['start_time'] : $saveData['start_date'];
    $end_event_date_str = !empty($saveData['end_time']) ? $saveData['end_date'] . ' ' . $saveData['end_time'] : $saveData['end_date'] . ' 23:59:59';
    if (strtotime($start_event_date_str) > strtotime($end_event_date_str)) {
      throw new ApiException(Status::CODE_FAIL, '开始时间不能早于结束时间');
    }
    $hasSchedule = [];
    $time = time();
    if (isset($param['_id']) && !empty($param['_id'])) {
      $hasSchedule = mongodb2()->schedule_list->findOne(['_id' => $param['_id']]);
      $hasSchedule = json_decode(json_encode($hasSchedule), true);
      if (!isset($hasSchedule['notice_date'])) {
        $saveData['notice_date'] = 0;
      }
      if ($hasSchedule['start_date'] == $saveData['start_date'] && $hasSchedule['end_date'] == $saveData['end_date']) {
        if (isset($hasSchedule['start_event_time']) && $hasSchedule['start_event_time'] > strtotime($start_event_date_str)) {
          $start_event_date_str = date('Y-m-d H:i:s', $hasSchedule['start_event_time']);
        }
        if (isset($hasSchedule['end_event_time']) && $hasSchedule['end_event_time'] > strtotime($end_event_date_str)) {
          $end_event_date_str = date('Y-m-d H:i:s', $hasSchedule['end_event_time']);
        }
      }
    }
    if ($saveData['is_loop'] == 1) {
      if (!empty($hasSchedule) && $hasSchedule['start_date'] == $saveData['start_date'] && $hasSchedule['end_date'] == $saveData['end_date'] && !$param['is_force']) {
        $saveData['start_event_time'] = $hasSchedule['start_event_time'];
        $saveData['end_event_time'] = $hasSchedule['end_event_time'];
        $saveData['step'] = $saveData['step'].'-step2';
      } else {
        $calc_event_time = $this->schedule->getNextTimePeriod(strtotime($start_event_date_str), strtotime($end_event_date_str), $saveData['date_type'], $saveData['loop_num'], $saveData['loop_type'], $param['is_force']);
        $saveData['start_event_time'] = $calc_event_time[0];
        $saveData['end_event_time'] = $calc_event_time[1];
        $saveData['step'] = $saveData['step'] . '-step3-'. $start_event_date_str.'-'. $end_event_date_str.'-'.json_encode($calc_event_time);
      }
    } else {
      $saveData['start_event_time'] = (int)strtotime($start_event_date_str);
      $saveData['end_event_time'] = (int)strtotime($end_event_date_str);
      $saveData['step'] = $saveData['step'] . '-step4';
    }
    $saveData['before_event_time'] = $saveData['start_event_time'];
    if ($saveData['notice_open'] == 1 && $saveData['before_num'] > 0) {
      $saveData['step'] = $saveData['step'] . '-step5';
      $saveData['before_event_time'] = $saveData['before_event_time'] - $saveData['before_num'] * 86400;
    }
    if (isset($param['_id']) && !empty($param['_id'])) {
      mongodb2()->schedule_list->updateOne(['_id' => $param['_id']], ['$set' => $saveData]);
      $data['_id'] = $param['_id'];
    } else {
      $saveData['_id'] = createId();
      $saveData['create_time'] = time();
      $saveData['is_finish'] = 0;
      $saveData['finish_time'] = 0;
      $saveData['notice_date'] = 0;
      mongodb2()->schedule_list->insertOne($saveData);
      $data['_id'] = $saveData['_id'];
    }
    return $this->response->json(Status::CODE_OK, 'success', $data);
  }
  public function notice()
  {
    $where = [];
    $today = strtotime(date('Y-m-d'));
    $time = time();
    $endOfDay = $today + 86399;
    $where['$or'][] = ['before_event_time'=>['$lte'=>$today]];
    $where['$or'][] = ['$and'=>[['start_event_time'=>['$lte'=> $today]], ['end_event_time'=>['$gte'=> $endOfDay]]]];
    $where['notice_date'] = ['$lt' => $today];
    $where['is_finish'] = 0;
    $where['notice_open'] = 1;
    $dataList = mongodb2()->schedule_list->find($where);
    $allData = [];
    foreach ($dataList as $doc) {
      $allData[] = (array)$doc;
    }
    foreach ($allData as $key => $vo) {
      if (!empty($vo['ps_id'])) {
        $pushData['ps_id'] = $vo['ps_id'];
        $pushData['msg_type'] = 'markdown';
        $pushData['params_json'] = json_encode(['title' => $vo['content'], 'time' => date('Y-m-d', $vo['start_event_time'])], JSON_UNESCAPED_UNICODE);
        // $pushData['template_data'] = (isset($smsData['template_data']) && !empty($smsData['template_data'])) ? $smsData['template_data'] : '';
        // $pushData['template_url'] = (isset($smsData['template_url']) && !empty($smsData['template_url'])) ? $smsData['template_url'] : '';
        // $pushData['template_touser'] = (isset($smsData['template_touser']) && !empty($smsData['template_touser'])) ? $smsData['template_touser'] : '';
        // $pushData['template_id'] = (isset($smsData['template_id']) && !empty($smsData['template_id'])) ? $smsData['template_id'] : '';
        $importance['gao'] = '高';
        $importance['zhong'] = '中';
        $importance['di'] = '低';
        if ($vo['before_event_time'] <= $time && $vo['start_event_time'] >= $time) {
          $saveData['before_event_time'] = $vo['start_event_time'];
          $pushData['title'] = '您有待处理日程即将开始';
          $pushData['content'] = '日程内容：' . $vo['content'] . '；日程时间：' . date('Y-m-d H:i:s', $vo['start_event_time']);
          $markdownNotice = " \n> **日程内容：**{$vo['content']} \n> **日程时间：**" . date('Y-m-d H:i:s', $vo['start_event_time']) . " \n>\n> **日程进度：**即将开始 \n> \n> **重要程度：**{$importance[$vo['importance']]} \n>\n> **[详情]** 请 [前往柠聚开发平台查看](https://console.21ds.cn/schedule/Calendar)";
        }else if ($vo['start_event_time'] < $time && $vo['end_event_time'] > $endOfDay) {
          $saveData['before_event_time'] = $vo['end_event_time'];
          $pushData['title'] = '您有待处理日程进行中';
          $pushData['content'] = '日程内容：' . $vo['content'] . '；日程时间：' . date('Y-m-d H:i:s', $vo['start_event_time']);
          $markdownNotice = " \n> **日程内容：**{$vo['content']} \n> **日程时间：**" . date('Y-m-d H:i:s', $vo['start_event_time']) . " \n>\n> **日程进度：**进行中 \n> \n> **重要程度：**{$importance[$vo['importance']]} \n>\n> **[详情]** 请 [前往柠聚开发平台查看](https://console.21ds.cn/schedule/Calendar)";
        }else if ($vo['end_event_time'] < $time) {
          $pushData['title'] = '您有待处理日程逾期未处理';
          $pushData['content'] = '日程内容：' . $vo['content'] . '；日程时间：' . date('Y-m-d H:i:s', $vo['start_event_time']);
          $markdownNotice = " \n> **日程内容：**{$vo['content']} \n> **日程时间：**" . date('Y-m-d H:i:s', $vo['start_event_time']) . " \n>\n> **日程进度：**逾期未处理 \n> \n> **重要程度：**{$importance[$vo['importance']]} \n>\n> **[详情]** 请 [前往柠聚开发平台查看](https://console.21ds.cn/schedule/Calendar)";
        }
        $pushData['msg_content'] = "#### 待处理日程通知\n> **日程详情** \n> {$markdownNotice}";
        (new Common)->doSendPush($pushData, null, $vo['developer_id']);
      }
      $saveData['notice_date'] = $today;
      mongodb2()->schedule_list->updateOne(['_id' => $vo['_id']], ['$set' => $saveData]);
    }
    return $this->response->json(Status::CODE_OK, 'success', ['allData'=>$allData,'where'=>$where]);
  }
}
